package com.module.aichat.ui.chatMain

import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.utls.HeadTitleUtils
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.postDelay
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.ViewUtils.initRecyclerView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.aichat.R
import com.module.aichat.data.bean.InputModel
import com.module.aichat.data.protocol.messageContent.TextMessageContent
import com.module.aichat.databinding.AichatActivityChatMainBinding
import com.module.aichat.db.table.DBMessage
import com.module.aichat.repo.ChatMessageRepo
import com.module.aichat.ui.widget.inputview.AiSbListAdapter
import com.module.aichat.ui.widget.inputview.ChatEditorCompat
import com.module.aichat.ui.widget.inputview.ChatInputListener
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import java.io.File

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/06/25
 * <p>
 * 描述：会话页面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_AICHAT_CHAT_MAIN)
class ChatMainActivity :
    AppActivity<AichatActivityChatMainBinding, ChatMainViewModel>(),
    View.OnClickListener, ChatInputListener, AiSbListAdapter.OnAiSbListAdapterListener {

    val TAG: String = ChatMainActivity::class.java.simpleName

    override fun getViewModel() = ChatMainViewModel::class.java

    override fun getViewContentBinding() =
        AichatActivityChatMainBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = false

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var mId: Int = 0

    @Autowired(name = KeyBundle.EXPAND_DATA)
    @JvmField
    var mQuestion: String? = ""

    //消息适配器
    private val mAdapter by lazy { AISingleChatAdapter(listener = this) }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        unEnableHandleHideSoftInput()

        //上下拉刷新
        mViewContentBinding.pdView.setEnableLoadMore(false)
        mViewContentBinding.pdView.setEnableLoadMoreWhenContentNotFull(false)
        getRefreshFooter()?.let { mViewContentBinding.pdView.setRefreshFooter(it) }
        mViewContentBinding.pdView.setRefreshHeader(
            ClassicsHeader(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )

        //会话列表适配器
        mViewContentBinding.hrv.apply {
//            initRecyclerView(this)
            adapter = mAdapter
            itemAnimator?.let {
                it.changeDuration = 0
                it.moveDuration = 0
                it.addDuration = 0
                it.removeDuration = 0
            }
            itemAnimator = null  // 完全禁用动画
        }
        mAdapter.addFooterView(layoutInflater.inflate(R.layout.base_rlv_margin_footer_tr_view100, null))
        var chatEditor =
            ChatEditorCompat.Build(mViewContentBinding.wrapperInputBox, mViewContentBinding.hrv)
                .bindListener(this) //绑定事件回调
                .builder()

        LiveEventBus.get(KeyEvents.KEY_AICHAT_RHV_ROLL_BOT).observe(this) {
            // 滑动RecyclerView到最底部
            mViewContentBinding.hrv.post {
                scrollChatListToBottom()
            }
        }

        LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND).observe(this) {
            mViewModel.chatMessages.value?.lastOrNull()?.let {dataIt->
                (dataIt.content as TextMessageContent).let { textMessageContentIt->
                    textMessageContentIt.text.isNullOrEmpty().no {
                        getProblemSuggestions()
                    }.otherwise {
                        mViewModel.deleteLastLoadingStatusData()
                    }
                }
            }

            postDelay(1500) {//延时1秒半
                mViewContentBinding.wrapperInputBox.getSendView().isEnabled = true
            }
//            mAdapter.data.lastOrNull()?.let { dataIt->
//               (dataIt.content as TextMessageContent).let { textMessageContentIt->
//                   textMessageContentIt.text.isNullOrEmpty().no {
//                       getProblemSuggestions()
//                   }
//               }
//            }
        }

        LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND_END).observe(this) {
        }

        LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND_ERROR).observe(this) {
            mViewModel.deleteLastLoadingStatusData()
            mViewContentBinding.wrapperInputBox.getSendView().isEnabled = true
        }
    }

    override fun initEvents() {
        super.initEvents()
//        mAdapter.addChildClickViewIds(R.id.scbLike, R.id.scbFall)
//        mAdapter.setOnItemChildClickListener(object : OnItemChildClickListener {
//            override fun onItemChildClick(
//                adapter: BaseQuickAdapter<*, *>,
//                view: View,
//                position: Int
//            ) {
//                when (view.id) {
//                    R.id.scbLike->{
//                        showToast(position)
//                    }
//                    R.id.scbFall->{
//                        showToast(position)
//                    }
//                }
//            }
//        })
//        mAdapter.setOnItemClickListener(object : OnItemClickListener {
//            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
//                when (view.id) {
//                    R.id.scbLike->{
//                        showToast(position)
//                    }
//                    R.id.scbFall->{
//                        showToast(position)
//                    }
//                }
//            }
//        })
        mViewContentBinding.pdView.setRefreshFooter(
            ClassicsFooter(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )

        mViewContentBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                mViewContentBinding.hrv.adapter?.notifyDataSetChanged()
                refreshLayout.layout.postDelayed({
                    finishPdView()
                }, 1000)
            }
        })

        //
        mViewContentBinding.wrapperInputBox.getAiSbListAdapter()
            .setOnItemClickListener { adapter, view, position ->
                mViewModel.sendTextMessage((adapter.data[position] as String), 0)
                mViewContentBinding.wrapperInputBox.setAiSbListAdapterData(arrayListOf())
            }

        LiveEventBus.get(KeyEvents.KEY_AICHAT_SEND_LIKE_STATE, DBMessage::class.java).observe(this) {
            requestMsgFeedback(it,"like")

        }
        LiveEventBus.get(KeyEvents.KEY_AICHAT_SEND_FALL_STATE, DBMessage::class.java).observe(this) {
            requestMsgFeedback(it,"dislike")
        }

        mViewContentBinding.tvTitle.setOnClickListener(onClick = this)
        mViewContentBinding.headTitleBack.setOnClickListener(onClick = this)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        // 观察ViewModel中的聊天消息列表变化
        mViewModel.chatMessages.observe(this) { messages ->
            mAdapter.setList(messages)

            // 自动滚动到底部
            if (messages.isNotEmpty()) {
                mViewContentBinding.hrv.postDelayed({
                    scrollChatListToBottom()
                }, 100)
            }
        }

        (mQuestion.isNullOrEmpty()).no {
            mViewModel.sendTextMessage(mQuestion ?: "", mId)
            mViewContentBinding.wrapperInputBox.getSendView().isEnabled = false
            mViewContentBinding.wrapperInputBox.setAiSbListAdapterData(arrayListOf())
        }
    }

    override fun onDestroy() {
        LiveEventBus.get(KeyEvents.KEY_AICHAT_STOP_AI_MSG).post(this)
        mViewModel.deleteLastLoadingStatusData()
        super.onDestroy()
    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.tvTitle ->{
                ChatMessageRepo.instance.delAll2DB()
                mAdapter.data.clear()
                mAdapter.notifyDataSetChanged()
                mViewModel.getDefData()
                mViewContentBinding.wrapperInputBox.setAiSbListAdapterData(arrayListOf())
            }
            mViewContentBinding.headTitleBack -> finish()
        }
    }

    private fun finishPdView() {
        mViewContentBinding.pdView.finishRefresh()
        mViewContentBinding.pdView.finishLoadMore()
        mViewContentBinding.pdView.setNoMoreData(true)
    }

    /**
     * 滑动聊天列表至最底部
     */
    private fun scrollChatListToBottom() {
        mViewContentBinding.hrv.scrollToPosition(mAdapter.itemCount - 1)
//        // 如果使用LinearLayoutManager
//        val layoutManager = mViewContentBinding.hrv.layoutManager as? LinearLayoutManager
//        layoutManager?.scrollToPositionWithOffset(mAdapter.itemCount - 1, 0)
    }

    /**
     * 获取可见item范围并刷新
     */
    private fun refreshVisibleItems() {
        val layoutManager = mViewContentBinding.hrv.layoutManager as LinearLayoutManager
        val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()
        val lastVisiblePosition = layoutManager.findLastVisibleItemPosition()

        // 使用 post 延迟执行，避免在布局过程中刷新
        mViewContentBinding.hrv.post {
            // 逐个刷新，避免批量操作导致的状态冲突
            for (position in firstVisiblePosition..lastVisiblePosition) {
                if (position >= 0 && position < mAdapter.itemCount) {
                    mAdapter.notifyItemChanged(position)
                }
            }
        }
    }

    private fun getProblemSuggestions() {
        mViewModel.getProblemSuggestions {
            showToast(it.message)
        }.observe(this) {
            val mList = it.Data as List<String>
            mList.isNullOrEmpty().no {
//                mViewContentBinding.wrapperInputBox.setAiSbListAdapterData(mList)
                mAdapter.data.lastOrNull()?.apply {
                    (this.targetId != "mConversationId").yes {//targetId=="mConversationId"的话就是自己发出的会话消息
                        this.extra = JsonUtils.toJson(mList)
                        mAdapter.notifyItemChanged(mAdapter.data.size-1)
                        mViewContentBinding.hrv.postDelayed({ scrollChatListToBottom() }, 100)
                    }

                    ChatMessageRepo.instance.add2DB(this)
                }
            }
        }
    }


    private fun requestMsgFeedback(message: DBMessage?, rating:String,) {
        if (mViewModel.isSendState) return

        var ratingTemp = ""
        (rating == "like").yes {
            ratingTemp = if ((message?.likeStatus?:0)>0) "" else rating
        }.otherwise {
            ratingTemp = if ((message?.fallStatus?:0)>0) "" else rating
        }

        showDialogLoading()

        mViewModel.requestMsgFeedback(message?.messageId?:"", ratingTemp) {
            showToast(it.message)
        }.observe(this) {
            dismissLoadingDialog()
            it.Data?.apply {

                mAdapter.data.forEach {dBMessageIt->
                    (this.message_id == dBMessageIt.messageId).yes {
                        (rating == "like").yes {
                            dBMessageIt.likeStatus = if (dBMessageIt.likeStatus >0) 0 else 1
                        }.otherwise {
                            dBMessageIt.fallStatus = if (dBMessageIt.fallStatus >0) 0 else 1
                        }
                        ChatMessageRepo.instance.add2DB(dBMessageIt)
                        doOnUiThread {
                            refreshVisibleItems()
                        }
                        return@forEach
                    }
                }

            }
        }
    }

    override fun sendText(text: String, userIds: List<String>?) {
        if (text.isNullOrEmpty()) return
//        showToast(text)
        //发送消息方法
        mViewModel.sendTextMessage(text, mId)
        mViewContentBinding.wrapperInputBox.getSendView().isEnabled = false
        mViewContentBinding.wrapperInputBox.setAiSbListAdapterData(arrayListOf())
    }

    override fun onChangeModel(inputModel: InputModel) {
        mViewContentBinding.hrv.postDelayed({ scrollChatListToBottom() }, 100)
    }

    override fun sendAudio(file: File, recordTime: Long) {
    }

    override fun toAtMember() {
    }

    override fun onAiSbListAdapterStr(mStr: String) {
        mViewModel.sendTextMessage(mStr, 0)
        mViewContentBinding.wrapperInputBox.getSendView().isEnabled = false
    }

}